package com.lechuang.user.manager.Impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.lechuang.common.model.BaseEntity;
import com.lechuang.common.result.Result;
import com.lechuang.member.dto.SaveMemberDto;
import com.lechuang.member.feign.MemberFeign;
import com.lechuang.member.vo.MemberDictCommonVo;
import com.lechuang.member.vo.MemberVo;
import com.lechuang.redis.utils.RedisUtils;
import com.lechuang.user.constants.LoginConstants;
import com.lechuang.user.entity.User;
import com.lechuang.user.dto.UserForgetPwdDto;
import com.lechuang.user.dto.UserLoginDto;
import com.lechuang.user.dto.UserRegisterDto;
import com.lechuang.user.manager.LoginManager;
import com.lechuang.user.manager.UserManager;
import com.lechuang.user.service.UserService;
import com.lechuang.user.util.InviteCodeBuildUtil;
import com.lechuang.user.util.LoginUtil;
import com.lechuang.user.vo.LoginVo;
import com.lechuang.web.exception.BusinessException;
import jakarta.annotation.Resource;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Objects;
import java.util.Random;

/**
 * @author apple
 * @version 1.0
 * @date 2024/6/21
 */
@Service
@Log4j2
public class LoginManagerImpl implements LoginManager {

    @Resource
    private UserService userService;

    @Resource
    private UserManager userManager;

    @Resource
    private MemberFeign memberFeign;

    @Value("${user.avatar}")
    private String avatar;
    @Value("${user.nickName}")
    private String nickName;

    @Override
    public LoginVo userLogin(UserLoginDto loginDto) {
        log.info("userLogin======>loginDto=====>{}", JSONUtil.toJsonStr(loginDto));
        String password = loginDto.getPassword();
        String phone = loginDto.getPhone();

        if (StrUtil.isBlank(phone) || StrUtil.isBlank(password)){
            throw new BusinessException("登录信息填写有误");
        }

        String key = LoginConstants.LOGIN_KEY + phone;

        String errNum = (String) RedisUtils.get(key);

        if (StrUtil.isNotBlank(errNum)) {

            if (Integer.parseInt(errNum) >= LoginConstants.ERR_NUM) {
                throw new BusinessException("账号已冻结，10分钟后再试");
            }
        }

        User user = userService.queryByPhone(phone);

        if (null == user) {
            redisCheck(errNum,key);
            throw new BusinessException("工号或密码错误，请重新输入");
        }
        //TODO:等加密
       // password = DigestUtils.md5Hex(password);

        if (!password.equals(user.getLoginPassword())) {

            redisCheck(errNum,key);
            throw new BusinessException("密码错误，请重新输入");
        }

        RedisUtils.del(key);

        LoginVo loginVo = BeanUtil.copyProperties(user, LoginVo.class);
        Result<MemberVo> memberVoResult = memberFeign.queryByUserId(user.getId());
        if (Objects.nonNull(memberVoResult) && Objects.nonNull(memberVoResult.getData())){
            loginVo.setMemberId(memberVoResult.getData().getId());
        }
        loginVo.setLoginDate(new Date());
        String token = LoginUtil.createToken(user);
        loginVo.setToken(token);
        RedisUtils.set(LoginConstants.getRedisKey(token),JSONUtil.toJsonStr(loginVo), LoginConstants.THIRTY_DAY);
        return loginVo;
    }

    @Override
    public LoginVo userRegister(UserRegisterDto userRegisterDto) {
        log.info("userRegister======>userRegisterDto=====>{}", JSONUtil.toJsonStr(userRegisterDto));
        String phone = userRegisterDto.getPhone();
        String validateCode = userRegisterDto.getValidateCode();
        String loginPassword = userRegisterDto.getLoginPassword();
        String confirmLoginPassword = userRegisterDto.getConfirmLoginPassword();
        String inviteCode = userRegisterDto.getInviteCode();
        //验证码验证
//        String  registerKey = LoginConstants.REGISTER_KEY + phone;
//
//        Object redisValidateCode = RedisUtils.get(registerKey);
//        if (Objects.isNull(redisValidateCode)) {
//            throw new BusinessException("验证码不存在或已过期，请重新获取!");
//        }
//        if (!Objects.equals(validateCode, redisValidateCode)) {
//            throw new BusinessException("验证码输入错误!");
//        }
//        if (!VerificationUtil.checkPassword(loginPassword)){
//            throw new BusinessException( "密码必须由8-16位数字和大小写字母组成");
//        }
//        if (!VerificationUtil.checkPassword(confirmLoginPassword)){
//            throw new BusinessException("确认密码必须由8-16位数字和大小写字母组成");
//        }
        if (!Objects.equals(loginPassword,confirmLoginPassword)){
            throw new BusinessException("密码输入不一致");
        }
        User user = userService.queryByPhone(phone);
        if (Objects.nonNull(user)){
            throw new BusinessException("该手机号已经注册");
        }

        User inviteUser = userService.queryByInviteCode(inviteCode);
        if (Objects.isNull(inviteUser)){
            throw new BusinessException("邀请人信息不存在");
        }
        //TODO:等加密
       // loginPassword = DigestUtils.md5Hex(loginPassword);
        User insertUser =new User()
                .setAvatar(avatar)
                .setNickName(nickName)
                .setPhone(phone)
                .setLoginPassword(loginPassword)
                .setInviteUserId(inviteUser.getId());
        userManager.saveUser(insertUser);
        LoginVo loginVo = BeanUtil.copyProperties(insertUser, LoginVo.class);
        return loginVo;
    }

    @Override
    public void userForgetPwd(UserForgetPwdDto userForgetPwdDto) {
        log.info("userForgetPwd======>userForgetPwdDto=====>{}", JSONUtil.toJsonStr(userForgetPwdDto));
        String phone = userForgetPwdDto.getPhone();
        String loginPassword = userForgetPwdDto.getLoginPassword();
        String confirmLoginPassword = userForgetPwdDto.getConfirmLoginPassword();
        String validateCode = userForgetPwdDto.getValidateCode();

        if (!Objects.equals(loginPassword,confirmLoginPassword)){
            throw new BusinessException("密码输入不一致");
        }
        //验证码验证
//        String  forgetKey = LoginConstants.FORGET_KEY + phone;
//        Object redisValidateCode = RedisUtils.get(forgetKey);
//        if (Objects.isNull(redisValidateCode)) {
//            throw new BusinessException("验证码不存在或已过期，请重新获取!");
//        }
//        if (!Objects.equals(validateCode, redisValidateCode)) {
//            throw new BusinessException("验证码输入错误!");
//        }

        User user = userService.queryByPhone(phone);
        if (Objects.isNull(user)){
            throw new BusinessException("手机号未注册");
        }

        if (loginPassword.equals(user.getLoginPassword())){
            throw new BusinessException("新密码与旧密码不能保持一致");
        }
        // TODO:密码待加密
        // loginPassword = DigestUtils.md5Hex(loginPassword);
        user.setLoginPassword(loginPassword);
        userService.updateById(user);
        SaveMemberDto saveMemberDto = new SaveMemberDto();
        saveMemberDto.setUserId(user.getId());
        saveMemberDto.setLoginPassword(loginPassword);
        saveMemberDto.setStatus(BaseEntity.STATUS_NORMAL);
        memberFeign.updateMemberByUserId(saveMemberDto);
    }

    @Override
    public void logout(String token) {
        String redisKey = LoginConstants.getRedisKey(token);
        RedisUtils.del(redisKey);
    }

    private void redisCheck(String errNum, String key) {
        int errNums = 1;

        if (StrUtil.isNotBlank(errNum)) {
            errNums = Integer.parseInt(errNum) + 1;
        }
        RedisUtils.set(key,String.valueOf(errNums),LoginConstants.TEN_MINUTE);
    }
}
